package com.ksm.server.service;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpRequestHandler;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

/**
 * servlet to handle file upload requests
 * 
 * @author hturksoy
 * 
 */
@Component("fileDownloadServlet")
public class FileDownloadServlet extends HttpServlet implements HttpRequestHandler {

	@Value("${file.directory.store}")
	public String storeDirectory;

	private static final String DEFAULT_STORE_DIR = "C://temp//ksm//store";
	private static final SimpleDateFormat FORMAT_DATE = new SimpleDateFormat("yyyyMMdd");

	private final static Logger LOGGER = Logger.getLogger(FileDownloadServlet.class);

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		perform(req, resp);
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPost(req, resp);
	}

	protected void perform(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		String requestFileName = req.getParameter("filename");

		if (requestFileName != null) {
			String fullFilename = getStoreDirectory() + "//" + requestFileName;
			String original_filename = requestFileName;

			File f = new File(fullFilename);
			if (f.isFile()) {
				int length = 0;
				ServletOutputStream op = resp.getOutputStream();
				ServletContext context = getServletConfig().getServletContext();
				String mimetype = context.getMimeType(fullFilename);

				//
				// Set the response and go!
				//
				//
				resp.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
				resp.setContentLength((int) f.length());
				resp.setHeader("Content-Disposition", "attachment; filename=\"" + original_filename + "\"");

				//
				// Stream to the requester.
				//
				byte[] bbuf = new byte[1];
				DataInputStream in = new DataInputStream(new FileInputStream(f));

				while ((in != null) && ((length = in.read(bbuf)) != -1)) {
					op.write(bbuf, 0, length);
				}

				in.close();
				op.flush();
				op.close();
			}
		}
	}

	@Override
	public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		LOGGER.debug("Handle Request Spring");
		doPost(req, resp);
	}

	/**
	 * 
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext());
		super.init(config);
	}

	public String getStoreDirectory() {
		return StringUtils.isEmpty(storeDirectory) ? DEFAULT_STORE_DIR : storeDirectory;
	}

}
